from django.db import models
from django.contrib.auth import get_user_model
from django.core.validators import FileExtensionValidator

User = get_user_model()

class MedicalImageRecognition(models.Model):
    """医疗图片识别记录"""
    RECOGNITION_TYPE_CHOICES = [
        ('symptom', '症状识别'),
        ('skin', '皮肤病识别'),
        ('oral', '口腔识别'),
        ('eye', '眼部识别'),
        ('other', '其他'),
    ]
    
    STATUS_CHOICES = [
        ('pending', '待识别'),
        ('processing', '识别中'),
        ('completed', '识别完成'),
        ('failed', '识别失败'),
    ]
    
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户')
    image = models.ImageField('上传图片', upload_to='medical_images/%Y/%m/%d/',
                             validators=[FileExtensionValidator(allowed_extensions=['jpg', 'jpeg', 'png'])])
    recognition_type = models.CharField('识别类型', max_length=20, choices=RECOGNITION_TYPE_CHOICES)
    status = models.CharField('状态', max_length=20, choices=STATUS_CHOICES, default='pending')
    
    # 百度AI识别结果
    raw_response = models.JSONField('原始响应', blank=True, null=True)
    recognized_items = models.JSONField('识别结果', blank=True, null=True)
    confidence_scores = models.JSONField('置信度', blank=True, null=True)
    
    # 医疗建议
    suggested_diseases = models.JSONField('疑似疾病', blank=True, null=True)
    suggested_department = models.CharField('建议科室', max_length=100, blank=True, null=True)
    medical_advice = models.TextField('医疗建议', blank=True, null=True)
    
    # 时间戳
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    processed_at = models.DateTimeField('处理时间', blank=True, null=True)
    
    class Meta:
        db_table = 'medical_image_recognition'
        verbose_name = '医疗图片识别'
        verbose_name_plural = '医疗图片识别'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.user.username} - {self.get_recognition_type_display()} - {self.get_status_display()}"

class MedicalDocumentOCR(models.Model):
    """医疗文档OCR识别记录"""
    DOCUMENT_TYPE_CHOICES = [
        ('blood_test', '血常规报告'),
        ('ct_report', 'CT报告'),
        ('mri_report', 'MRI报告'),
        ('ultrasound', '超声报告'),
        ('xray', 'X光片'),
        ('prescription', '处方单'),
        ('medical_record', '病历'),
        ('other', '其他'),
    ]
    
    STATUS_CHOICES = [
        ('pending', '待识别'),
        ('processing', '识别中'),
        ('completed', '识别完成'),
        ('failed', '识别失败'),
    ]
    
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户')
    document = models.ImageField('上传文档', upload_to='medical_documents/%Y/%m/%d/',
                                validators=[FileExtensionValidator(allowed_extensions=['jpg', 'jpeg', 'png', 'pdf'])])
    document_type = models.CharField('文档类型', max_length=20, choices=DOCUMENT_TYPE_CHOICES)
    status = models.CharField('状态', max_length=20, choices=STATUS_CHOICES, default='pending')
    
    # OCR识别结果
    raw_response = models.JSONField('原始响应', blank=True, null=True)
    extracted_text = models.TextField('提取文本', blank=True, null=True)
    structured_data = models.JSONField('结构化数据', blank=True, null=True)
    
    # 医疗数据解析
    medical_indicators = models.JSONField('医疗指标', blank=True, null=True)
    abnormal_values = models.JSONField('异常值', blank=True, null=True)
    doctor_diagnosis = models.TextField('医生诊断', blank=True, null=True)
    
    # 解读结果
    interpretation = models.TextField('解读结果', blank=True, null=True)
    recommendations = models.TextField('建议', blank=True, null=True)
    
    # 时间戳
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    processed_at = models.DateTimeField('处理时间', blank=True, null=True)
    
    class Meta:
        db_table = 'medical_document_ocr'
        verbose_name = '医疗文档OCR'
        verbose_name_plural = '医疗文档OCR'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.user.username} - {self.get_document_type_display()} - {self.get_status_display()}"

class MultiModalConsultation(models.Model):
    """多模态问诊记录"""
    STATUS_CHOICES = [
        ('draft', '草稿'),
        ('submitted', '已提交'),
        ('processing', '处理中'),
        ('completed', '已完成'),
        ('cancelled', '已取消'),
    ]
    
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户')
    consultation_id = models.CharField('问诊ID', max_length=50, unique=True)
    status = models.CharField('状态', max_length=20, choices=STATUS_CHOICES, default='draft')
    
    # 症状描述
    symptom_description = models.TextField('症状描述', blank=True, null=True)
    duration = models.CharField('持续时间', max_length=100, blank=True, null=True)
    severity = models.IntegerField('严重程度', choices=[(i, f'{i}级') for i in range(1, 11)], blank=True, null=True)
    
    # 关联的识别记录
    image_recognition = models.ForeignKey(MedicalImageRecognition, on_delete=models.SET_NULL, 
                                         blank=True, null=True, verbose_name='图片识别记录')
    document_ocr = models.ForeignKey(MedicalDocumentOCR, on_delete=models.SET_NULL, 
                                    blank=True, null=True, verbose_name='文档OCR记录')
    
    # 综合分析结果
    ai_analysis = models.JSONField('AI分析结果', blank=True, null=True)
    suggested_department = models.CharField('建议科室', max_length=100, blank=True, null=True)
    urgency_level = models.CharField('紧急程度', max_length=20, choices=[
        ('low', '低'),
        ('medium', '中'),
        ('high', '高'),
        ('emergency', '紧急')
    ], blank=True, null=True)
    
    # 医生信息
    assigned_doctor = models.ForeignKey('Home.Doctor', on_delete=models.SET_NULL, 
                                       blank=True, null=True, verbose_name='分配医生')
    doctor_notes = models.TextField('医生备注', blank=True, null=True)
    
    # 时间戳
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    completed_at = models.DateTimeField('完成时间', blank=True, null=True)
    
    class Meta:
        db_table = 'multi_modal_consultation'
        verbose_name = '多模态问诊'
        verbose_name_plural = '多模态问诊'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"问诊 {self.consultation_id} - {self.user.username}"

class MedicalKnowledgeBase(models.Model):
    """医疗知识库"""
    CATEGORY_CHOICES = [
        ('disease', '疾病'),
        ('symptom', '症状'),
        ('treatment', '治疗'),
        ('medication', '药物'),
        ('examination', '检查'),
        ('department', '科室'),
    ]
    
    title = models.CharField('标题', max_length=200)
    category = models.CharField('分类', max_length=20, choices=CATEGORY_CHOICES)
    content = models.TextField('内容')
    keywords = models.JSONField('关键词', default=list, blank=True)
    related_diseases = models.JSONField('相关疾病', default=list, blank=True)
    department = models.CharField('相关科室', max_length=100, blank=True, null=True)
    
    # 关联信息
    severity_level = models.IntegerField('严重程度', choices=[(i, f'{i}级') for i in range(1, 6)], blank=True, null=True)
    common_symptoms = models.JSONField('常见症状', default=list, blank=True)
    recommended_tests = models.JSONField('推荐检查', default=list, blank=True)
    
    # 元数据
    is_active = models.BooleanField('是否启用', default=True)
    view_count = models.IntegerField('浏览次数', default=0)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    
    class Meta:
        db_table = 'medical_knowledge_base'
        verbose_name = '医疗知识库'
        verbose_name_plural = '医疗知识库'
        ordering = ['-created_at']
    
    def __str__(self):
        return self.title